package com.fable.web.controller.product;

import com.alibaba.fastjson.JSON;
import com.fable.biz.operate.CreateAttributeModel;
import com.fable.biz.operate.CreateProductModel;
import com.fable.common.config.RequireLogin;
import com.fable.common.constant.FableConstant;
import com.fable.common.utils.JsonResult;
import com.fable.dal.dto.AdminUserDTO;
import com.fable.dal.mapper.ext.AttributeExtMapper;
import com.fable.dal.mapper.ext.FileRecordExtMapper;
import com.fable.dal.mapper.ext.ProductExtMapper;
import com.fable.dal.model.*;
import com.fable.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by weishuai on 18/7/21.
 */
@Controller
@RequireLogin
@RequestMapping("/product")
public class ProductController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    ProductExtMapper productExtMapper;

    @Autowired
    AttributeExtMapper attributeExtMapper;

    @Autowired
    FileRecordExtMapper fileRecordExtMapper;


    @RequestMapping("/productList.htm")
    public String list( ModelMap model) {
        ProductQuery query=new ProductQuery();
        query.createCriteria().andStatusGreaterThanOrEqualTo(0);
        query.setOrderByClause(" id desc");
        List<ProductDO> list= productExtMapper.selectByQuery(query);
        model.put("list", list);
        AttributeQuery attributeQuery=new AttributeQuery();
        attributeQuery.setOrderByClause(" id desc ");
        attributeQuery.createCriteria().andStatusGreaterThanOrEqualTo(0);
        List<AttributeDO> attributeDOList=attributeExtMapper.selectByQuery(attributeQuery);

        model.put("attributeList",attributeDOList);
        return "product/productList";
    }

    @RequestMapping("/productAdd.htm")
    public String add(HttpServletRequest request, ModelMap model,Integer id) {
        //id不为空则说明是点击修改过来的
        if(id!=null){
            ProductDO productDO= productExtMapper.selectByPrimaryKey(id);
            model.put("result",productDO);
        }
        return "product/productAdd";
    }

    @RequestMapping("/productDetail.htm")
    public String productDetail(HttpServletRequest request, ModelMap model,Integer id) {
        //id不为空则说明是点击修改过来的
        ProductDO productDO=null;
        if(id!=null){
            productDO= productExtMapper.selectByPrimaryKey(id);
            model.put("result",productDO);
        }

        model.put("fileRecordList",getFileList(productDO.getProductFileIds()));
        return "product/productDetail";
    }

    private List<FileRecordDO> getFileList(String fileIds) {
        List<FileRecordDO> fileRecordList=new ArrayList<>();
        if (StringUtil.isNotBlank(fileIds)) {
            if (StringUtil.isNotBlank(fileIds)) {
                List<String> fileIdList = Arrays.asList(StringUtil.split(fileIds, ","));
                for (String fileId : fileIdList) {
                    FileRecordDO fileRecordDO = fileRecordExtMapper.selectByPrimaryKey(Long.parseLong(fileId));
                    if (fileRecordDO != null) {
                        fileRecordList.add(fileRecordDO);
                    }
                }
            }
        }
        return fileRecordList;
    }

    @RequestMapping("/delProduct.json")
    @ResponseBody
    public JsonResult delete(HttpServletRequest request, Integer id) {
        JsonResult result = new JsonResult();
        AdminUserDTO adminDO = (AdminUserDTO) request.getSession().getAttribute(FableConstant.USER_SESSION_KEY);
        if (adminDO == null) {
            result.setErrMsg("请重新登录!");
            return result;
        }
        if (id != null) {
            ProductDO attributeDO= productExtMapper.selectByPrimaryKey(id);
            if (attributeDO == null) {
                result.setErrMsg("对象不存在!");
                return result;
            } else {
                attributeDO.setStatus(-1);
                attributeDO.setGmtModified(new Date());
                productExtMapper.updateByPrimaryKeySelective(attributeDO);
            }
        }
        return result;
    }

    @RequestMapping("/saveProduct.json")
    @ResponseBody
    public JsonResult saveAdminRole(HttpServletRequest request, @ModelAttribute CreateProductModel createProductModel) {
        JsonResult jsonResult = new JsonResult();
//        AdminUserDO adminDO = (AdminUserDO) request.getSession().getProduct(FableConstant.USER_SESSION_KEY);
//        if (adminDO == null) {
//            jsonResult.setCustomErrCode("-1", "未登录");
//            return jsonResult;
//        }
        try {
            if (checkExist(createProductModel)) {
                jsonResult.setErrMsg("已存在产品!");
                return jsonResult;
            }
            if (createProductModel.getId() != null) {
                ProductDO productDO= productExtMapper.selectByPrimaryKey(createProductModel.getId());
                if(productDO==null){
                    logger.error("非法操作,param:{}", JSON.toJSONString(createProductModel));
                    jsonResult.setErrMsg("非法操作!");
                    return jsonResult;
                }
                BeanUtils.copyProperties(createProductModel, productDO);
                productExtMapper.updateByPrimaryKeySelective(productDO);
            }else{
                ProductDO productDO=new ProductDO();
                BeanUtils.copyProperties(createProductModel, productDO);
                productDO.setGmtModified(new Date());
                productDO.setGmtCreate(new Date());
                productExtMapper.insertSelective(productDO);
            }
        } catch (Exception e) {
            logger.error("保存属性异常,param:{}", JSON.toJSONString(createProductModel), e);
            jsonResult.setErrMsg("保存异常请联系管理员!");
            return jsonResult;
        }
        return jsonResult;
    }

    private boolean checkExist(@ModelAttribute CreateProductModel createProductModel) {
//        ProductQuery query=new ProductQuery();
//        query.createCriteria().andStatusGreaterThanOrEqualTo(0).andProductNameEqualTo(createProductModel.getName());
//        List<ProductDO> list=productExtMapper.selectByQuery(query)  ;
//        if(!CollectionUtils.isEmpty(list)){
//            logger.warn("已存在属性,param:{}", JSON.toJSONString(createProductModel));
//            return true;
//        }
        return false;
    }
}
